package com.vaye.im.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import lombok.extern.slf4j.Slf4j;

/**
 * 分类名称
 *
 * @author wangzhiyong
 * @module admin
 * @date 2024年04月25日 下午2:24
 */
@Slf4j
public class WebSocketAuthHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FullHttpRequest) {
            FullHttpRequest request = (FullHttpRequest) msg;
            // 这里添加权限认证逻辑，例如检查HTTP头部或查询参数
            if (authenticate(request)) {
                ctx.fireChannelRead(msg); // 认证通过，继续处理
            } else {
                // 认证失败，关闭连接或返回错误响应
                ctx.close();
            }
        } else if (msg instanceof WebSocketFrame) {
            ctx.fireChannelRead(msg); // 如果是WebSocket消息，则继续
        } else {
            super.channelRead(ctx, msg);
        }
        super.channelRead(ctx, msg);
    }

    private boolean authenticate(FullHttpRequest request) {
        // 这里实现你的认证逻辑，比如检查token或session
        // 返回true表示认证通过，false表示失败
        HttpHeaders headers = request.headers();
        if (headers.size() < 1) {
            return false;
        }
        String uid = headers.get("Sec-WebSocket-Protocol");
        log.debug("Authentication success. uid: {}", uid);
        if (!"qwe123".equals(uid)) {
            return false;
        }
        return true;
    }
}
